#pragma once
#include <pthread.h>
#include <queue>
#include <list>
#include "data.h"

class thread_pool;
class thread
{
	pthread_t _pid;
	thread_pool *_tp;

	static void *func(void *obj)
	{
		pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
		pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
		thread *o = static_cast<thread*>(obj);
		o->pthread_func();
	}

public:
	thread(): _tp(NULL), _pid(-1){};
	thread(thread_pool *tp): _tp(tp), _pid(-1){};

	int start(){
		return pthread_create(&_pid, NULL, func, this);
	}
	
	int cancel(){
		if(_pid != -1){
			pthread_cancel(_pid);
			_pid = -1;
		}
	}

	int wait(){
		if(_pid != -1)
		  pthread_join(_pid, 0);
		_pid = -1;
	}

	virtual int thread_func() = 0;
};

class server;
class thread_pool
{
	server *_server;
	std::vector<thread *> _thread_vec;
	int _thread_num;
	bool _stop;
	
	int _serial;
	
public:
	thread_pool(): _thread_num(7), _stop(false), _server(NULL), _serial(1){}; 

	void set_thread_num(int i) { _thread_num = i; }

	void set_server(server* s){_server = s;}
	server *get_server(){return _server;}
	
	bool has_stoped(){return _stop;}
	
	void* get_zmq();
	database *get_data_base();
	
	int start();
	int stop();
};

